package c;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;

public class TcpEchoServer {
    ServerSocket serverSocket = null;
    public TcpEchoServer (int port) throws IOException {
        serverSocket = new ServerSocket(port);
    }
    public void start() throws IOException {
        System.out.println("服务器启动!");
        while (true) {

            Socket clientSocket = serverSocket.accept();
            Thread t =new Thread(()->{
                try {
                    processConnection(clientSocket);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            });
            t.start();





        }

    }
    //通过这个方法来处理连接
    public void processConnection(Socket clientSocket) throws IOException {
        //1 打印一个日志,告知当前有客户端连上了
        System.out.printf("[%s:%d] 客户端上线!\n", clientSocket.getInetAddress(), clientSocket.getPort());
        //2. 从clientSocket对象中获取到流对象,来进一步的进行后续的操作
            try (InputStream inputStream = clientSocket.getInputStream();
                 OutputStream outputStream = clientSocket.getOutputStream()) {
                //3. 也需要一个循环,针对每个连接,客户端都可能会发来多个请求,服务器也就需要返回多个响应
                while (true) {
                Scanner scanner = new Scanner(inputStream);
                //3.1 读取请求并解析
                if (!scanner.hasNext()) {
                    //如果发现后续没有数据了,此时说明TCP的连接已经是断开了的
                    System.out.printf("[%s : %d] 客户端下线\n", clientSocket.getInetAddress(), clientSocket.getPort());
                    break;
                }

                String request = scanner.next();
                //3.2 根据 请求计算响应
                String response = process(request);
                //3.3 将响应写回到客户端
                outputStream.write(response.getBytes());
                System.out.printf("[%s :%d ]  , req= %s ,resp= %s" ,clientSocket.getInetAddress(),clientSocket.getPort(),
                        request,response);


            }
        }finally {
                //即使当前的processConnection在不同的线程中被调用,也可以正确的关闭
                clientSocket.close();
       }
    }
    //根据请求计算响应
    //由于是回显服务器,直接把请求作为响应返回回去

    private String process(String request) {
        //给响应这里后面加上一个换行符,使客户端读取响应的时候,也有明确的空白符
        return request+"\n";
    }

    public static void main(String[] args) throws  IOException {
        TcpEchoServer2 tcpEchoServer = new TcpEchoServer2(9090);
        tcpEchoServer.start();

        }
}
